package org.jeik.beackBeans;

import java.io.File;
import java.io.IOException;

import org.jeik.beackBeans.contents.PageContentsBean;
import org.jeik.common.Constants;
import org.jeik.controllers.NavigationController;
import org.jeik.controllers.NavigationRule;
import org.jeik.data.models.Service;
import org.jeik.data.models.User;
import org.jeik.utils.Configs;
import org.jeik.utils.WebUtils;

/**
 * 
 * @author AAsha
 *
 */
public class AppSessionBean {
	
	private User user;
	private Service service = new Service();
	
	/**
	 * 
	 */
	public AppSessionBean() {
	}
	
	/**
	 * 
	 */
	public void openServicePage(){
		
		Object serviceId = WebUtils.getRequest().getParameter("SERVICE_ID");
		if(serviceId == null){
			return;
		}
		
		PageContentsBean pageContentsBean = (PageContentsBean) WebUtils.resolveExpression(WebUtils.PAGE_CONTENTS_BEAN, PageContentsBean.class);
		
		for(Service s:pageContentsBean.getServices()){
			if(s.getId().equals(Long.valueOf(serviceId.toString()))){
				service = s;
				break;
			}
		}
		
		NavigationController.navigate(NavigationRule.SERVICE_PAGE);
	}
	
	/**
	 * 
	 */
	public void openServicePage(String serviceId){
		
		if(serviceId == null){
			return;
		}
		
		PageContentsBean pageContentsBean = (PageContentsBean) WebUtils.resolveExpression(WebUtils.PAGE_CONTENTS_BEAN, PageContentsBean.class);
		
		for(Service s:pageContentsBean.getServices()){
			if(s.getId().equals(Long.valueOf(serviceId))){
				service = s;
				break;
			}
		}
		
		NavigationController.navigate(NavigationRule.SERVICE_PAGE);
	}
	
	/**
	 * 
	 * @return
	 */
	public String openPage(String pageNav){
		if(pageNav == null){
			return "";
		}
		
		return pageNav.toString();
	}
	
	/**
	 * 
	 * @throws IOException
	 */
	public void downloadFile() throws IOException{
		
		Object fileName = WebUtils.getRequest().getParameter("FILE_NAME");
		if(fileName == null){
			return;
		}
		
		File filesDir = new File(Configs.getConfigValue(Constants.Configs.FILES_DIR));
        File file = new File(filesDir, fileName.toString());
        
        if(file.exists()){
        	WebUtils.downloadFile(file);
        }
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Service getService() {
		return service;
	}

	public void setService(Service service) {
		this.service = service;
	}
	
	
	
}
